import Core.Gadget as Gadget
import Core.WindFunctions as Wind
import datetime
import DataProcess


# ---业绩预告信息---
def Download_ProfitNotice(database, instrument, reportDate, logger):
    #
    symbol = instrument["symbol"]
    # print("Try to Collect Profit Notice", symbol, reportDate)
    # ---Field----
    contents = [];
    #
    contents.append("profitnotice_abstract")  # rptdate 业绩预告摘要
    contents.append("profitnotice_reason")  # rptdate 业绩预告变动原因
    contents.append("profitnotice_style")  # rptdate 业绩预告类型
    contents.append("profitnotice_date")  # rptdate 业绩预告最新披露日期
    contents.append("profitnotice_firstdate")  # rptdate 业绩预告首次披露日期
    contents.append("profitnotice_change")  # rptdate 预告净利润变动幅度(%)
    contents.append("profitnotice_lasteps")  # rptdate 去年同期每股收益
    contents.append("profitnotice_netprofitmax")  # rptdate 预告净利润上限
    contents.append("profitnotice_netprofitmin")  # rptdate 预告净利润下限
    contents.append("profitnotice_changemax")  # rptdate 预告净利润同比增长上限
    contents.append("profitnotice_changemin")  # rptdate 预告净利润同比增长下限

    # ---Necessary Parameters---
    params = {}
    datestr = Gadget.ToDateString(reportDate)
    params["rptDate"] = datestr
    params["unit"] = 1

    # ---Request Functions---
    values = Wind.WSS(symbol, contents, params)[0]
    # return values

    # 该报告期无预告数据
    if values["profitnotice_date"] < datetime(1900, 1, 1):
        print("该报告期无预告数据", reportDate.date())
        return

    print(" *** Collect Profit Notice *** ", symbol, reportDate)

    # ---Generate Document---
    dataObject = {}
    for k, v in values.items():
        dataObject[k] = values[k]
    #
    dataObject["Period"] = Gadget.ReportPeriod(reportDate)
    dataObject["Report_Date"] = reportDate  # Gadget.ToDateTimeString(reportDate)
    releaseDateTime = values["profitnotice_date"]
    # releaseDateTime = releaseDateTime.replace(microsecond=0)  # Dirty Datetime
    releaseDate = releaseDateTime.date()
    dataObject["Release_Date"] = releaseDateTime
    dataObject["DateTime"] = releaseDateTime
    dataObject["Date"] = releaseDate
    #
    dataObject["Symbol"] = symbol
    dataObject["Key2"] = symbol + "_ProfitNotice_" + Gadget.ToDateString(reportDate) + "_" + Gadget.ToDateString(releaseDate)

    # ---Upsert to Database---
    target = {}
    target["Report_Date"] = reportDate
    target["Release_Date"] = releaseDate
    target["Symbol"] = symbol
    database.Upsert("Stock", "Profit_Notice", target, dataObject)
    pass
    # ---


# ---业绩快报信息---
def Download_PerformanceExpress(database, instrument, reportDate, logger):
    #
    symbol = instrument["symbol"]

    # ---Field----
    contents = [];
    contents.append("performanceexpress_lastdate")  # rptdate 业绩快报最新披露日期
    contents.append("performanceexpress_date")  # rptdate 业绩快报首次披露日期
    contents.append("performanceexpress_perfexincome")  # rptdate 业绩快报:营业收入
    contents.append("performanceexpress_perfexprofit")  # rptdate 业绩快报:营业利润
    contents.append("performanceexpress_perfextotalprofit")  # rptdate 业绩快报:利润总额
    contents.append("performanceexpress_perfexnetprofittoshareholder")  # rptdate 业绩快报:归母净利润
    contents.append("performanceexpress_perfexepsdiluted")  # rptdate 业绩快报:每股收益EPS-基本
    contents.append("performanceexpress_perfexroediluted")  # rptdate 业绩快报:净资产收益率ROE-加权
    contents.append("performanceexpress_perfextotalassets")  # rptdate 业绩快报:总资产
    contents.append("performanceexpress_perfexnetassets")  # rptdate 业绩快报:净资产
    contents.append("performanceexpress_or_yoy")  # rptdate 业绩快报:同比增长率:营业收入
    contents.append("performanceexpress_op_yoy")  # rptdate 业绩快报:同比增长率:营业利润
    contents.append("performanceexpress_ebt_yoy")  # rptdate 业绩快报:同比增长率:利润总额
    contents.append("performanceexpress_np_yoy")  # rptdate 业绩快报:同比增长率:归母净利润
    contents.append("performanceexpress_eps_yoy")  # rptdate 业绩快报:同比增长率:基本每股收益
    contents.append("performanceexpress_roe_yoy")  # rptdate 业绩快报:同比增长率:加权平均净资产收益率
    contents.append("performanceexpress_income_ya")  # rptdate 业绩快报:去年同期营业收入
    contents.append("performanceexpress_profit_ya")  # rptdate 业绩快报:去年同期营业利润
    contents.append("performanceexpress_totprofit_ya")  # rptdate 业绩快报:去年同期利润总额
    contents.append("performanceexpress_netprofit_ya")  # rptdate 业绩快报:去年同期净利润
    contents.append("performanceexpress_eps_ya")  # rptdate 业绩快报:去年同期每股收益
    contents.append("performanceexpress_bps")  # rptdate 业绩快报:每股净资产
    contents.append("performanceexpress_netassets_b")  # rptdate 业绩快报:期初净资产
    contents.append("performanceexpress_bps_b")  # rptdate 业绩快报:期初每股净资产
    contents.append("performanceexpress_eqy_growth")  # rptdate 业绩快报:比年初增长率：归母的股东权益
    contents.append("performanceexpress_bps_growth")  # rptdate 业绩快报:比年初增长率：归母的每股净资产
    contents.append("performanceexpress_totassets_growth")  # rptdate 业绩快报:比年初增长率：总资产

    # ---Necessary Parameters---
    params = {}
    datestr = Gadget.ToDateString(reportDate)
    params["rptDate"] = datestr
    params["unit"] = 1

    # ---Request Functions---
    values = Wind.WSS(symbol, contents, params)[0]
    # return values

    # 该报告期无预告数据
    if values["performanceexpress_lastdate"] < datetime(1900, 1, 1):
        print("该报告期无预告数据 Performance Express", reportDate.date())
        return

    print(" *** Collect Performance Express *** ", symbol, reportDate)

    # ---Generate Document---
    dataObject = {}
    for k, v in values.items():
        dataObject[k] = values[k]

    dataObject["Period"] = Gadget.ReportPeriod(reportDate)
    dataObject["Report_Date"] = reportDate  # Gadget.ToDateTimeString(reportDate)
    releaseDateTime = values["performanceexpress_lastdate"]
    # releaseDateTime = releaseDateTime.replace(microsecond=0)  # Dirty Datetime
    releaseDate = releaseDateTime.date()
    dataObject["Release_Date"] = releaseDateTime
    dataObject["DateTime"] = releaseDateTime
    dataObject["Date"] = releaseDate
    #
    dataObject["Symbol"] = symbol
    dataObject["Key2"] = symbol + "_PerformanceExpress_" + Gadget.ToDateString(reportDate) + "_" + Gadget.ToDateString(releaseDate)

    # ---Upsert to Database---
    target = {}
    target["Report_Date"] = reportDate
    target["Release_Date"] = releaseDate
    target["Symbol"] = symbol
    database.Upsert("Stock", "Performance_Express", target, dataObject)


def Batch_Download_ExpressNotice(database, datetime1=None, datetime2=None, startIndex=0, logger=None):
    #
    if datetime2 == None:
        datetime2 = datetime.now()
    if datetime1 == None:
        datetime1 = datetime2

    # ---生成所有可能的ReportDate---
    # reportDateTimes = Gadget.GenerateReportDates(datetime1, datetime2)
    reportDateTimes = Gadget.FromDateRangeToFindReportDate(datetime1, datetime2)

    #
    instruments = database.Find("Instruments", "Stock")

    # 添加自动去重功能
    existedByDate = {}
    # existedByDate = DataProcess.GetExsited(database, databaseName="stock", tableName="ProfitNotice", reportDates = reportDateTimes)
    # DataProcess.Download_Data_ByDate2(database, instruments, reportDateTimes, Download_ProfitNotice, startIndex=0, logger=logger, existedByDate=existedByDate)

    # existedByDate = DataProcess.GetExsited(database, databaseName="stock", tableName="PerformanceExpress", reportDates = reportDateTimes)
    DataProcess.Download_Data_ByDate2(database, instruments, reportDateTimes, Download_PerformanceExpress, startIndex=0, logger=logger, existedByDate=existedByDate)


if __name__ == '__main__':

    from Core.Config import *
    config = Config()
    database = config.DataBase()
    logger = config.Logger("ExpressNotice")
    Wind.w.start()  # 启动Wind API

    datetime1 = datetime(2010, 1, 1)
    datetime2 = datetime(2020, 3, 31)
    Batch_Download_ExpressNotice(database, datetime1=datetime1, datetime2=datetime2 , startIndex=1, logger=logger)